import sun.awt.VerticalBagLayout;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;

/**
 * Created by IntelliJ IDEA.
 * User: xsicrz
 * Date: 6/6/11
 * Time: 8:16 AM
 * To change this template use File | Settings | File Templates.
 */
public class TimelineFrame extends JFrame {

    private static final Insets insets = new Insets(10,10, 10, 10);

    private JComboBox monthCombobox;
    private JTextField yearTextField;
    private JButton buttonOk;
    private Model model = null;

    public TimelineFrame() {
        super("Timelinator v1.0");
        init();
    }

    private void init() {
        this.setSize(800, 700);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        monthCombobox = new JComboBox();

        for(DateUtils.CustomDate date : DateUtils.getMonths()) {
            monthCombobox.addItem(date);
        }

        yearTextField = new JTextField();
        Calendar cal = Calendar.getInstance();
        int month = cal.get(Calendar.MONTH);
        int year = cal.get(Calendar.YEAR);

        monthCombobox.setSelectedIndex(month);
        yearTextField.setText(""+year);
        JLabel label = new JLabel("Sélectionner le mois et l'année");

        buttonOk = new JButton("OK");


        yearTextField.setMinimumSize(new Dimension(50,20));
        yearTextField.setMaximumSize(new Dimension(50, 20));
        yearTextField.setPreferredSize(new Dimension(50, 20));


        JPanel selectionPanel = new JPanel();
        selectionPanel.setLayout(new GridBagLayout());
        selectionPanel.add(label, new GridBagConstraints(0,0, 1, 1, 0, 0, GridBagConstraints.NORTHEAST, GridBagConstraints.HORIZONTAL, insets, 0,0));
        selectionPanel.add(monthCombobox);
        selectionPanel.add(yearTextField);
        selectionPanel.add(buttonOk);

        JPanel tablePanel = new JPanel();

        model = null;
        try {
            model = Model.deserialize();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ClassNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        if(model == null) {
            model = new Model();
        }



        final TimelineTableModel tableModel = new TimelineTableModel(model, month, year);
        final JTable table = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setMinimumSize(new Dimension(700, 550));
        scrollPane.setMaximumSize(new Dimension(700, 550));
        scrollPane.setPreferredSize(new Dimension(700, 550));

        table.setDefaultRenderer(Object.class, new TimelineTableCellRenderer(tableModel));
        table.setFillsViewportHeight(true);
        tablePanel.add(scrollPane);

        this.setLayout(new VerticalBagLayout());
        this.add(selectionPanel);
        this.add(tablePanel);

        JPanel panelSave = new JPanel();
        JButton buttonSave = new JButton("Enregistrer");

        JButton buttonPrint = new JButton("Imprimer");

        JButton buttonCsv = new JButton("Export csv");




        buttonSave.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    Model.serialize(TimelineFrame.this.model);
                    JOptionPane.showMessageDialog(TimelineFrame.this,  "Sauvegarde OK");
                } catch(Exception err) {
                    JOptionPane.showMessageDialog(TimelineFrame.this,  "Sauvegarde KO");

                }
            }
        });

        buttonPrint.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                PrintUtilities.printComponent(table);
            }
        });
        buttonOk.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int year = Integer.valueOf(yearTextField.getText());
                int month = ((DateUtils.CustomDate)monthCombobox.getSelectedItem()).getMonth();
                tableModel.setSelectedMonth(month);
                tableModel.setSelectedYear(year);
                tableModel.fireTableDataChanged();
            }
        });

        buttonCsv.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                int val = fileChooser.showDialog(TimelineFrame.this, "Choisir");
                if(val == 0) {
                    File file = fileChooser.getSelectedFile();
                    BufferedWriter bufferedWriter = null;
                    try {
                         bufferedWriter = new BufferedWriter(new FileWriter(file));
                        //Write column names
                        for(int i = 0; i < tableModel.getColumnCount(); i++) {
                            String columnName = tableModel.getColumnName(i);
                            if(columnName == null) {
                                columnName = "";
                            }
                            bufferedWriter.append(columnName+";");
                        }
                        bufferedWriter.newLine();
                        for(int i = 0; i < tableModel.getRowCount(); i++) {
                            for(int j = 0; j < tableModel.getColumnCount(); j++) {
                                Object value = tableModel.getValueAt(i, j);
                                String valueStr = "";
                                if(value != null) {
                                    valueStr = value.toString();
                                }

                                bufferedWriter.append(valueStr+";");
                            }
                            bufferedWriter.newLine();
                        }
                        bufferedWriter.flush();
                        JOptionPane.showMessageDialog(TimelineFrame.this, "CSV créé.");
                    } catch (IOException e1) {
                        e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                    } finally {
                        try {
                            bufferedWriter.close();
                        } catch (IOException e1) {
                            e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                        }
                    }
                }


            }
        });

        this.addWindowListener(new WindowListener() {
            @Override
            public void windowOpened(WindowEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void windowClosing(WindowEvent e) {
                int save = JOptionPane.showConfirmDialog(TimelineFrame.this, "Voulez-vous sauvegarder?");
                if(save == 0) {
                    try {
                        Model.serialize(TimelineFrame.this.model);
                        JOptionPane.showMessageDialog(TimelineFrame.this,  "Sauvegarde OK");
                    } catch(Exception err) {
                        JOptionPane.showMessageDialog(TimelineFrame.this,  "Sauvegarde KO");

                    }
                }
            }

            @Override
            public void windowClosed(WindowEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void windowIconified(WindowEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void windowDeiconified(WindowEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void windowActivated(WindowEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void windowDeactivated(WindowEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
            }
        });

        panelSave.add(buttonSave);
        panelSave.add(buttonPrint);
        panelSave.add(buttonCsv);
        this.add(panelSave);
        this.setVisible(true);


    }
}
